package com.tddx.activiti.business.sys.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tddx.activiti.business.sys.dao.systuser.SysTuserDao;
import com.tddx.activiti.business.sys.entity.systuser.SysTuserEntity;
import com.tddx.activiti.filter.realm.AuthorRealm.Principal;
import com.tddx.activiti.utils.IDataTemplate;
import com.tddx.activiti.utils.StringUtils;

@Component
public class SysTuserUtil implements IDataTemplate {
	
	private static String USER_ID = "USER_ID_";
	private static String USER_NAME = "USER_NAME_";
	
	@Autowired private SysTuserDao dao;
	private static Map<String, Object> map = new HashMap<String, Object>();
	Logger log = Logger.getLogger(getClass());

	@Override
	public void init() {
		log.info("加载用户数据开始。。。。。");
		List<SysTuserEntity> list = dao.findAll();
		for(SysTuserEntity entity: list){
			map.put(USER_NAME + entity.getVcUsername(), entity);
			map.put(String.valueOf(USER_ID + entity.getId()), entity);
		}
		log.info("加载用户数据结束。。。。。");
	}

	public static String getNameByUserId(String id) {
		return getUserByUserId(id).getVcName();
	}

	public static SysTuserEntity getUserByUserId(String key) {
		if(key.indexOf(USER_ID)<0){
			key = USER_ID + key;
		}
		return (SysTuserEntity) map.get(key);
	}
	
	public static String getNameByUserName(String vcUsername) {
		return getUserByUserId(vcUsername).getVcName();
	}
	
	public static SysTuserEntity getUserByUserName(String key) {
		if(key.indexOf(USER_NAME)<0){
			key = USER_NAME + key;
		}
		System.out.println(map);
		return (SysTuserEntity) map.get(key);
	}
	
	/**
	 * 获取当前用户
	 * @return
	 */
	public static SysTuserEntity getCurrentUser(){
		String vcUserName = getCurrentUserName();
		if(StringUtils.isEmpty(vcUserName)){
			return null;
		}
		SysTuserEntity entity = getUserByUserName(vcUserName);
		return entity;
	}
	
	/**
	 * 获取当前用户名
	 */
	public static String getCurrentUserName(){
		Principal principal = getPrincipal();
		if(principal==null){
			return null;
		}
		String vcUserName = principal.getVcUserName();
		return vcUserName;
	}
	
	/**
	 * 用户是否登陆
	 */
	public static boolean existUser(){
		if(getPrincipal()==null){
			return false;
		}
		return true;
	}
	
	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}
		}catch (Exception e) {
			
		}
		return null;
	}
	
}
